package org.hilo.boot.app.web;

import org.springframework.http.MediaType;
import org.springframework.web.servlet.View;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * 
 * @author zollty
 * @since 2017年6月6日
 */
public class SimpleJsonView implements View {
    
    private final String json;

    private int statusCode = 200;
    
    public SimpleJsonView(String json) {
        this.json = json;
    }

    public SimpleJsonView(String json, int statusCode) {
        this.json = json;
        this.statusCode = statusCode;
    }

    @Override
    public String getContentType() {
        return MediaType.APPLICATION_JSON_VALUE;
    }

    @Override
    public void render(Map<String, ?> model, 
            HttpServletRequest request, HttpServletResponse response) throws Exception {

        writeJsonResponse(response, json);
    }
    
    
    private void writeJsonResponse(HttpServletResponse response, String message) throws IOException {
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("utf-8");
        response.setStatus(statusCode);
        PrintWriter writer = response.getWriter();
        writer.println(message);
        writer.flush();
    }

}
